package com.situ.controller;

import com.situ.context.BaseContext;
import com.situ.domain.entity.TAddress;
import com.situ.domain.dto.AddressDTO;
import com.situ.domain.dto.UpdateAddressDTO;
import com.situ.service.AddressService;
import com.situ.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Tag(name = "地址管理")
@RestController
@RequestMapping("/address")
@RequiredArgsConstructor
public class AddressController {

    private final AddressService addressService;

    @GetMapping("/getAddressList")
    @Operation(summary = "查询当前用户的地址列表")
    public Result<List<TAddress>> getAddressList() {
        List<TAddress> list = addressService.lambdaQuery()
                .eq(TAddress::getUid, BaseContext.getCurrentId())
                .list().stream().peek(item -> item.setPhone(item.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"))).toList();
        return Result.success(200, "查询成功", list);
    }


    @PostMapping("/addAddress")
    @Operation(summary = "添加地址接口")
    public Result addAddress(@RequestBody AddressDTO addressDTO) {
        Integer currentId = BaseContext.getCurrentId();
        log.info("添加地址:{},{}", addressDTO,currentId);
        addressService.addAddress(addressDTO,currentId);
        return Result.ok("添加成功");
    }


    /**
     * 删除地址
     * @param id 地址id
     * @return
     */
    @DeleteMapping("/deleteAddress/{id}")
    @Operation(summary = "删除地址接口")
    public Result deleteAddress(@PathVariable Integer id) {
        log.info("删除地址:{}", id);
        return addressService.removeById(id) ? Result.ok("删除成功") : Result.failure("删除失败");
    }


    /**
     * 设置默认地址
     * @param id 地址id
     * @return
     */
    @Operation(summary = "设置默认地址接口")
    @PutMapping("/setDefaultAddress/{id}")
    public Result setDefaultAddress(@PathVariable Integer id) {
        log.info("设置默认地址:{}", id);
        addressService.setDefaultAddress(id);
        return  Result.ok("设置成功");
    }

    /**
     * 修改地址
     * @param addressDTO
     * @return
     */
    @Operation(summary = "修改地址接口")
    @PutMapping("/updateAddress")
    public Result updateAddress(@RequestBody UpdateAddressDTO addressDTO) {
        log.info("修改地址:{}", addressDTO);
        addressService.updateAddress(addressDTO);
        return Result.ok("修改成功");
    }


    @GetMapping("/getAddressById/{id}")
    @Operation(summary = "根据id查询地址接口")
    public Result<TAddress> getAddressById(@PathVariable Integer id) {
        TAddress address = addressService.getById(id);
        return Result.success(200, "查询成功", address);
    }

}



